//index.js
const utils = require("../../utils/utils.js");
const biz = require("../../utils/bizUtils.js");
const listUtil = require("../../utils/listUtil.js");
const session = require("../../utils/session.js");
const toast = require("../../utils/toasts.js");
const wxm = require("../../utils/wechat_modules.js");
const com = require("../../utils/commonRequest.js");
const cache = require("../../utils/cache.js");

import {
  order_pay,
  req
} from "../../utils/api.js";

//获取应用实例
const app = getApp()
const globalData = app.globalData;

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    list: [],
    hidden: true,
    scrollTop: 0,
    scrollHeight: 0,
    title: '',
    keyword: null,
    catId: null,
    orderRule: 'HOT',
    waiting: true,
    share_modal: false,
    noMore: false,
    banners: ['https://img.lingxing.site/jx/banner400_3_1.png'],
    isIphoneX: globalData.isIphoneX,
    showAllStaffs: false,
    flowStr: '选择教练->支付订金->到驾校支付尾款->学车->考试->拿到驾照->评价服务。\n注：订金在支付尾款前可全额退款，安全无忧。'
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function(options) {
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        console.info(res.windowHeight);
        that.setData({
          scrollHeight: res.windowHeight
        });
      }
    });

    if (options) {
      if (options.id) {
        this.setData({
          id: options.id
        });
      }

      if (options.from) {
        this.setData({
          from: options.from
        })
      }


      if (options.salesId) {
        this.setData({
          salesId: options.salesId
        })
        if (options.salesName) {}
      }

      if (options.index) {
        this.setData({
          index: options.index
        });
      }

      if (options.type) {
        this.setData({
          type: options.type,
        })
      }
    }

    session.login(this.refreshMe);
  },
  refreshMe: function(usr) {
    this.setData({
      user: usr
    });
    toast.showLoading();

    this.getData();
  },
  onShow: function() {
    var staff = cache.pop('staffSelect');
    if (staff) {
      this.setData({
        staff: staff
      })
      this.saveStaff();
    }
  },
  getData() {
    var id = this.data.id;
    if (!id) {
      wxm.showModal({
        title: '订单不存在',
        content: '你查找的订单不存在或已经关闭',
        hideCancel: true,
        isIt: (true)
      }).then(() => {
        wx.navigateBack({

        })
        return;
      }).catch(() => {});
      return;
    }

    var that = this;
    req('/order/detail', {
      id: id
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var obj = res.result;
        obj.addressStr = biz.addressStr(obj);
        obj.bizTime = obj.openTime + '-' + obj.closeTime;
        obj.timeStr = utils.tf('yyyy-M-d', obj.createdTime);
        obj.statusStr = biz.orderStatusStr(obj.status);
        obj.opStr = biz.orderStatusOpStr(obj.status);
        obj.jx1TimeStr = utils.tf('yyyy-M-d', obj.jx1Time);
        obj.jx2TimeStr = utils.tf('yyyy-M-d', obj.jx2Time);
        obj.jx3TimeStr = utils.tf('yyyy-M-d', obj.jx3Time);
        obj.jx4TimeStr = utils.tf('yyyy-M-d', obj.jx4Time);
        obj.jxJzTimeStr = utils.tf('yyyy-M-d', obj.jxJzTime);

        if(obj.servantId) {
          var staff = {};
          staff.id = obj.servantId;
          staff.realName = obj.servantName;
          that.setData({
            staff
          });
        }

        that.setData({
          obj
        });
        this.getSeller();
      } else {
        toast.show(res.errorMsg);
      }
    });
  },
  getSeller() {
    var id = this.data.obj.sellerId;
    var that = this;
    req('/seller/jxDetail', {
      id: id
    }).then(res => {
      // console.log(res);
      if (res.success) {
        var obj = res.result;
        obj.rates = biz.rates(obj.score);
        obj.rateTip = '专业:9.0 设施:9.5 服务:9.2';
        obj.addressStr = biz.addressStr(obj);
        obj.bizTime = obj.openTime + '-' + obj.closeTime;
        that.setData({
          seller: obj
        });
      } else {
        toast.show(res.errorMsg);
      }
    });
  },
  pushFormSubmit: function(e) {
    console.log(e);
    console.log("formId:" + e.detail.formId);
    com.saveFormId(e);
  },
  gotoMap: function() {
    var obj = this.data.seller;
    biz.gotoMap({
      title: obj.name,
      lat: obj.lat,
      lng: obj.lng,
      address: obj.addressStr
    });
  },
  tel: function() {
    wxm.makePhoneCall(this.data.seller.tel);
  },
  showAllStaffs: function() {
    var showAllStaffs = this.data.showAllStaffs;
    this.setData({
      showAllStaffs: !showAllStaffs
    })
  },
  gotoSellerDetail: function() {
    var seller = this.data.seller;
    wx.navigateTo({
      url: '/pages/sellerDetail/sellerDetail?id=' + seller.id,
    })
  },
  back: function() {
    wxm.back(this);
  },
  selectStaff: function() {
    var obj = this.data.obj;
    var status = obj.status;
    if (status != 'CREATE' && status != 'PAY') {
      return;
    }
    wx.navigateTo({
      url: '/pages/staffList/staffList?type=select&sellerId=' + this.data.obj.sellerId,
    })
  },
  buy: function() {
    var that = this;
    var param = {};
    param.id = this.data.id;

    toast.showLoading();
    order_pay(param).then(res => {
      if (res.success) {
        var obj1 = res.result;

        wx.requestPayment({
          timeStamp: obj1.timeStamp,
          nonceStr: obj1.nonceStr,
          package: obj1.package,
          signType: obj1.signType,
          paySign: obj1.paySign,
          success(res) {
            wxm.showModal({
              title: '下单成功',
              content: '请到驾校支付尾款，祝您早日拿到驾照',
              hideCancel: true,
              isIt: (true)
            }).then(() => {
              that.getData();
            }).catch(() => {});
          },
          fail(res) {
            that.getData();
          }
        })
        return;

      } else {
        toast.show(res.errorMsg);
        that.getData();
      }
    });
  },
  saveStaff() {
    var id = this.data.id;
    var staff = this.data.staff;
    if (!staff) {
      return;
    }
    var that = this;
    req('/order/changeServant', {
      id: id,
      servantId: staff.id
    }).then(res => {
      // console.log(res);
      if (res.success) {
        wxm.showModal({
          title: '操作成功',
          content: '支付尾款成功后，教练会联系您，请保持手机畅通',
          hideCancel: true,
          isIt: (true)
        }).then(() => { }).catch(() => { });
      } else {}
    });
  },
  gotoList: function() {
    wx.switchTab({
      url: '/pages/orderList/orderList',
    })
  },
  op: function() {
    var obj = this.data.obj;
    var status = obj.status;
    if (status == 'CREATE') {
      this.buy();
    } else if (status == 'PAY') {
      this.payTail();
    } else if (status == 'JX_JZ' || status == 'FINISH' || status == 'RATE') {
      this.rate();
    } else {
      this.tel();
    }
  },
  payTail: function() {
    wxm.showModal({
      title: '尾款说明',
      content: '请到驾校支付尾款，祝您早日拿到驾照',
      hideCancel: true,
      isIt: (true)
    }).then(() => {}).catch(() => {});
  },
  rate:function() {
    wx.navigateTo({
      url: '/pages/rateAdd/rateAdd?id='+this.data.id,
    })
  }
})